<?php


class BooksLine_Action extends Typecho_Widget implements Widget_Interface_Do
{
    private $db;
    private $prefix;
    private $options;

    function bookInsert(){
        if (BooksLine_Plugin::form('insert')->validate()) {
            $this->response->goBack();
        }
        /** 取出数据 */
        $book = $this->request->from('name', 'author', 'info', 'date');

        /** 插入数据 */
        $book['id'] = $this->db->query($this->db->insert($this->prefix.'booksline')->rows($book));

        /** 提示信息 */
        $this->widget('Widget_Notice')->set(_t('书籍 <a href="%s">%s</a> 已经被增加',
            $book['name'], $book['author']), NULL, 'success');

        /** 转向原页 */
        $this->response->redirect(Typecho_Common::url('extending.php?panel=BooksLine%2Fmanage-books.php', $this->options->adminUrl));
    }


    function bookUpdate(){
        if (BooksLine_Plugin::form('update')->validate()) {
            $this->response->goBack();
        }

        /** 取出数据 */
        $book = $this->request->from('id','name', 'author', 'info', 'date');

        /** 更新数据 */
        $this->db->query($this->db->update($this->prefix.'booksline')->rows($book)->where('id = ?', $book['id']));


        /** 提示信息 */
        $this->widget('Widget_Notice')->set(_t('书籍 <a href="%s">%s</a> 已经被更新',
            $book['name'], $book['author']), NULL, 'success');

        /** 转向原页 */
        $this->response->redirect(Typecho_Common::url('extending.php?panel=BooksLine%2Fmanage-books.php', $this->options->adminUrl));
    }


    function bookDelete(){

        $ids = $this->request->filter('int')->ids;
        $deleteCount = 0;
        if ($ids && is_array($ids)) {
            foreach ($ids as $id) {
                if ($this->db->query($this->db->delete($this->prefix.'booksline')->where('id = ?', $id))) {
                    $deleteCount ++;
                }
            }
        }
        /** 提示信息 */
        $this->widget('Widget_Notice')->set($deleteCount > 0 ? _t('书籍已经删除') : _t('没有书籍被删除'), NULL,
            $deleteCount > 0 ? 'success' : 'notice');

        /** 转向原页 */
        $this->response->redirect(Typecho_Common::url('extending.php?panel=BooksLine%2Fmanage-books.php', $this->options->adminUrl));
    }


    public function action()
    {
        $this->db = Typecho_Db::get();
        $this->prefix = $this->db->getPrefix();
        $this->options = Typecho_Widget::widget('Widget_Options');
        $this->on($this->request->is('do=insert'))->bookInsert();
        $this->on($this->request->is('do=update'))->bookUpdate();
        $this->on($this->request->is('do=delete'))->bookDelete();
        $this->response->redirect($this->options->adminUrl);
    }
}